<?php
require_once ('..'.DIRECTORY_SEPARATOR.'initialize.php');
include_once(Utils::getPath(array('shared', 'template.php')));
include_once(Utils::getPath(array('repositories', 'userRepository.php')));

$referer = getenv("HTTP_REFERER");
$friendId = null;
$action = null;

if(isset($_GET['delete']))
{
	$friendId = $_GET['delete'];
	$action = 'delete';
}
else if(isset($_GET['add']))
{
	$friendId = $_GET['add'];
	$action = 'add';
}else{
    Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);
}

if(!is_null($friendId) && $_SESSION['authenticated'])
{
	$userRep = new UserRepository();
	$user = $userRep->getById($friendId);

	if(!isset($user))
	{
            Utils::goToErrorPage();
	}
	
	if($action == 'delete')
	{
		$userRep->removeFriends($_SESSION['authenticatedId'],$friendId);
	}else if($action == 'add')
	{
		$state = $userRep->getFriendsState($_SESSION['authenticatedId'],$friendId);
		
		if(is_null($state)) //INVITE
			$userRep -> setFriends($_SESSION['authenticatedId'], $friendId, false);
		else if($state[1])//ACCEPT
			$userRep -> setFriends($_SESSION['authenticatedId'], $friendId, true); 		
	}else{
            Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);
        }
}

header("Location: $referer");
exit();
?>